package cn.ad.handler;

import cn.ad.enumration.MaterialFormat;
import com.alibaba.druid.util.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用于获取原生模版素材规格列表时，素材格式类型的转换 
 * 在Java中为String：jpg,png 
 * 在数据库中为String：1,2
 * 
 * @author yu-juan.zhang
 * @from 2016-07-01
 * @since V1.0
 *
 */
@MappedTypes({java.lang.String.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class MaterialFormatStringTypeHandler extends BaseTypeHandler<String> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, parameter);
	}

	/***
	 * 把数据库类型转化为Java类型
	 */
	@Override
	public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return this.getMaterialFormatStringTypeForJavaObject(rs.getString(columnName));
	}

	@Override
	public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return this.getMaterialFormatStringTypeForJavaObject(rs.getString(columnIndex));
	}

	@Override
	public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return this.getMaterialFormatStringTypeForJavaObject(cs.getString(columnIndex));
	}

	private String getMaterialFormatStringTypeForJavaObject(String formatType) {
		if (!StringUtils.isEmpty(formatType)) {
			// 根据素材格式枚举类，将素材格式枚举值转化为对应的描述： 1,2 -> jpg,png
			StringBuilder bufferFormatType = new StringBuilder();
			String[] format = formatType.split(",");
			for (String value : format) {
				try {
					bufferFormatType.append(MaterialFormat.forDescription(Integer.valueOf(value))).append(",");
				} catch (NumberFormatException ex) {
					throw new NumberFormatException("没有对应的素材格式枚举值：" + value);
				}
			}
			if (bufferFormatType.toString().endsWith(",")) {
				formatType = bufferFormatType.toString().substring(0, bufferFormatType.toString().lastIndexOf(","));
			} else {
				formatType = bufferFormatType.toString();
			}
		}
		return formatType;
	}
}
